package com.uduemc.biso.node.web.component.html;

import com.uduemc.biso.node.core.common.entities.SiteComponent;
import com.uduemc.biso.node.core.common.udinpojo.ComponentArticlesData;
import com.uduemc.biso.node.core.common.udinpojo.common.ImageConfig;
import com.uduemc.biso.node.core.common.udinpojo.componentarticles.*;
import com.uduemc.biso.node.core.entities.*;
import com.uduemc.biso.node.core.entities.custom.Article;
import com.uduemc.biso.node.core.entities.custom.CategoryQuote;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.utils.ComponentUtil;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.component.SpringContextUtils;
import com.uduemc.biso.node.web.component.html.inter.HISystemComponentUdin;
import com.uduemc.biso.node.web.service.byfeign.SystemService;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Component
public class HComponentArticlesUdin implements HISystemComponentUdin {

    private static String name = "component_articles";

    @Resource
    private BasicUdin basicUdin;

    @Resource
    private SiteUrlComponent siteUrlComponent;

    // 是否通过 surface 的方式渲染
    static boolean surface = true;

    @Override
    public StringBuilder html(SPage page, SSystem system, SCategories categories, SiteComponent siteComponent) {
        StringBuilder stringBuilder = new StringBuilder();
        String config = siteComponent.getComponent().getConfig();
        ComponentArticlesData componentArticlesData = ComponentUtil.getConfig(config, ComponentArticlesData.class);
        if (componentArticlesData == null || StringUtils.isEmpty(componentArticlesData.getTheme())) {
            return stringBuilder;
        }
        List<Article> articles = siteComponent.getArticles();
        ComponentArticlesDataConfig componentArticlesDataConfig = componentArticlesData.getConfig();
        if (componentArticlesDataConfig == null || CollectionUtils.isEmpty(articles)) {
            return stringBuilder;
        }

        if (surface) {
            return surfaceRender(page, system, categories, siteComponent, componentArticlesData, componentArticlesDataConfig, articles);
        }

        return render(page, system, categories, siteComponent, componentArticlesData, componentArticlesDataConfig, articles);

    }

    protected StringBuilder surfaceRender(SPage page, SSystem system, SCategories categories, SiteComponent siteComponent,
                                          ComponentArticlesData componentArticlesData, ComponentArticlesDataConfig componentArticlesDataConfig, List<Article> articles) {
        StringBuilder stringBuilder = new StringBuilder();
        int showSort = componentArticlesDataConfig.getShowSort();
        int showTime = componentArticlesDataConfig.getShowTime();
        String ratio = componentArticlesDataConfig.getRatioData();
        String viewDetaits = componentArticlesDataConfig.getViewDetaits();
        if (StringUtils.isEmpty(viewDetaits)) {
            viewDetaits = "查看详情";
        }
        int vis = componentArticlesDataConfig.getVis();

        List<ComponentArticlesDataQuote> quote = new ArrayList<ComponentArticlesDataQuote>(articles.size());
        String[] monthsInEng = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
        List<DateString> date = new ArrayList<>(articles.size());
        for (Article article : articles) {
            SArticle sArticle = article.getSArticle();
            CategoryQuote categoryQuote = article.getCategoryQuote();
            RepertoryQuote repertoryQuote = article.getRepertoryQuote();
            HRepertory hRepertory = repertoryQuote == null ? null : repertoryQuote.getHRepertory();
            SRepertoryQuote sRepertoryQuote = repertoryQuote == null ? null : repertoryQuote.getSRepertoryQuote();
            if (sArticle == null) {
                continue;
            }

            String src = siteUrlComponent.getImgEmptySrc();
            String alt = "";
            String title = "";
            if (hRepertory != null) {
                src = siteUrlComponent.getImgSrc(hRepertory);
            }
            if (sRepertoryQuote != null) {
                String configSRepertoryQuote = sRepertoryQuote.getConfig();
                ImageConfig imageConfig = ComponentUtil.getConfig(configSRepertoryQuote, ImageConfig.class);
                if(imageConfig != null) {
                	if (StringUtils.hasText(imageConfig.getAlt())) {
                        alt = imageConfig.getAlt();
                    }
                    if (StringUtils.hasText(imageConfig.getTitle())) {
                        title = imageConfig.getTitle();
                    }
                }
            }

            SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
            SSystemItemCustomLink sSystemItemCustomLink = null;
            try {
                sSystemItemCustomLink = systemServiceImpl.findOkOneByHostSiteSystemItemId(sArticle.getHostId(), sArticle.getSiteId(), sArticle.getSystemId(),
                        sArticle.getId());
            } catch (IOException e) {
            }

            String linkHref = siteUrlComponent.getArticleHref(page, sArticle, sSystemItemCustomLink);
            if (categories != null) {
                linkHref = siteUrlComponent.getArticleHref(page, categories, sArticle);
            } else if (categoryQuote != null && categoryQuote.getSCategories() != null) {
                linkHref = siteUrlComponent.getArticleHref(page, categoryQuote.getSCategories(), sArticle);
            }

            String cateHref = "";
            if (categoryQuote != null && categoryQuote.getSCategories() != null) {
                cateHref = siteUrlComponent.getCategoryHref(page, categoryQuote.getSCategories());
            }

            ComponentArticlesDataQuoteImage componentArticlesDataQuoteImage = new ComponentArticlesDataQuoteImage();
            componentArticlesDataQuoteImage.setSrc(src).setAlt(alt).setTitle(title);
            ComponentArticlesDataQuoteLink componentArticlesDataQuoteLink = new ComponentArticlesDataQuoteLink();
            componentArticlesDataQuoteLink.setHref(linkHref).setTarget(componentArticlesDataConfig.getAtarget());
            ComponentArticlesDataQuoteCateLink componentArticlesDataQuoteCateLink = new ComponentArticlesDataQuoteCateLink();
            componentArticlesDataQuoteCateLink.setHref(cateHref).setTarget(componentArticlesDataConfig.getCtarget());

            String dataTitle = sArticle.getTitle();
            String dataInfo = sArticle.getSynopsis();
            if (StringUtils.isEmpty(dataInfo)) {
                dataInfo = "";
            }

            String cateTitle = "";
            if (categoryQuote != null && categoryQuote.getSCategories() != null) {
                cateTitle = categoryQuote.getSCategories().getName();
            }
            Date datetime = sArticle.getReleasedAt();

            ComponentArticlesDataQuote componentArticlesDataQuote = new ComponentArticlesDataQuote();

            componentArticlesDataQuote.setCateLink(componentArticlesDataQuoteCateLink).setCateTitle(cateTitle).setDataInfo(dataInfo).setDataTitle(dataTitle)
                    .setDatetime(datetime).setImage(componentArticlesDataQuoteImage).setLink(componentArticlesDataQuoteLink);

            quote.add(componentArticlesDataQuote);
            DateString dateString = new DateString();
            if (datetime != null) {
                LocalDateTime localDateTime = LocalDateTime.ofInstant(datetime.toInstant(), ZoneId.systemDefault());
                int year = localDateTime.getYear();
                int monthValue = localDateTime.getMonthValue();
                int dayOfMonth = localDateTime.getDayOfMonth();
                int hour = localDateTime.getHour();
                int minute = localDateTime.getMinute();
                int second = localDateTime.getSecond();
                dateString.setYear(String.valueOf(year)).setMonth(monthValue < 10 ? "0" + monthValue : String.valueOf(monthValue))
                        .setDay(dayOfMonth < 10 ? "0" + dayOfMonth : String.valueOf(dayOfMonth)).setHours(hour < 10 ? "0" + hour : String.valueOf(hour))
                        .setMinutes(minute < 10 ? "0" + minute : String.valueOf(minute)).setSeconds(second < 10 ? "0" + second : String.valueOf(second))
                        .setMonthsEng(monthsInEng[monthValue - 1]);
            }
            date.add(dateString);
        }

        String titleStyle = componentArticlesData.getTitleStyle();
        if (StringUtils.hasText(titleStyle)) {
            titleStyle = "style=\"" + titleStyle + "\"";
        }

        Map<String, Object> mapData = new HashMap<>();
        mapData.put("comid", siteComponent.getComponent().getId());
        mapData.put("id", "product-id-" + DigestUtils.md5DigestAsHex(String.valueOf(siteComponent.getComponent().getId()).getBytes()));
        mapData.put("titleStyle", titleStyle);
        mapData.put("showSort", showSort);
        mapData.put("showTime", showTime);
        mapData.put("ratio", ratio);
        mapData.put("viewDetaits", viewDetaits);
        mapData.put("vis", vis);
        mapData.put("quote", quote);
        mapData.put("date", date);

        StringWriter render = basicUdin.render(name, "surface_render", mapData);
        stringBuilder.append(render);

        return stringBuilder;
    }

    protected StringBuilder render(SPage page, SSystem system, SCategories categories, SiteComponent siteComponent, ComponentArticlesData componentArticlesData,
                                   ComponentArticlesDataConfig componentArticlesDataConfig, List<Article> articles) {
        StringBuilder stringBuilder = new StringBuilder();
        int showSort = componentArticlesDataConfig.getShowSort();
        int showTime = componentArticlesDataConfig.getShowTime();
        String ratio = componentArticlesDataConfig.getRatioData();
        String viewDetaits = componentArticlesDataConfig.getViewDetaits();
        if (StringUtils.isEmpty(viewDetaits)) {
            viewDetaits = "查看详情";
        }
        int vis = componentArticlesDataConfig.getVis();

        List<ComponentArticlesDataQuote> quote = new ArrayList<ComponentArticlesDataQuote>(articles.size());
        String[] monthsInEng = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
        List<DateString> date = new ArrayList<>(articles.size());
        for (Article article : articles) {
            SArticle sArticle = article.getSArticle();
            CategoryQuote categoryQuote = article.getCategoryQuote();
            RepertoryQuote repertoryQuote = article.getRepertoryQuote();
            HRepertory hRepertory = repertoryQuote == null ? null : repertoryQuote.getHRepertory();
            SRepertoryQuote sRepertoryQuote = repertoryQuote == null ? null : repertoryQuote.getSRepertoryQuote();
            if (sArticle == null) {
                continue;
            }

            String src = siteUrlComponent.getImgEmptySrc();
            String alt = "";
            String title = "";
            if (hRepertory != null) {
                src = siteUrlComponent.getImgSrc(hRepertory);
            }
            if (sRepertoryQuote != null) {
                String configSRepertoryQuote = sRepertoryQuote.getConfig();
                ImageConfig imageConfig = ComponentUtil.getConfig(configSRepertoryQuote, ImageConfig.class);
                if (StringUtils.hasText(imageConfig.getAlt())) {
                    alt = imageConfig.getAlt();
                }
                if (StringUtils.hasText(imageConfig.getTitle())) {
                    title = imageConfig.getTitle();
                }
            }

            SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
            SSystemItemCustomLink sSystemItemCustomLink = null;
            try {
                sSystemItemCustomLink = systemServiceImpl.findOkOneByHostSiteSystemItemId(sArticle.getHostId(), sArticle.getSiteId(), sArticle.getSystemId(),
                        sArticle.getId());
            } catch (IOException e) {
            }
            String linkHref = siteUrlComponent.getArticleHref(page, sArticle, sSystemItemCustomLink);
            if (categories != null) {
                linkHref = siteUrlComponent.getArticleHref(page, categories, sArticle);
            } else if (categoryQuote != null && categoryQuote.getSCategories() != null) {
                linkHref = siteUrlComponent.getArticleHref(page, categoryQuote.getSCategories(), sArticle);
            }

            String cateHref = "";
            if (categoryQuote != null && categoryQuote.getSCategories() != null) {
                cateHref = siteUrlComponent.getCategoryHref(page, categoryQuote.getSCategories());
            }

            ComponentArticlesDataQuoteImage componentArticlesDataQuoteImage = new ComponentArticlesDataQuoteImage();
            componentArticlesDataQuoteImage.setSrc(src).setAlt(alt).setTitle(title);
            ComponentArticlesDataQuoteLink componentArticlesDataQuoteLink = new ComponentArticlesDataQuoteLink();
            componentArticlesDataQuoteLink.setHref(linkHref).setTarget(componentArticlesDataConfig.getAtarget());
            ComponentArticlesDataQuoteCateLink componentArticlesDataQuoteCateLink = new ComponentArticlesDataQuoteCateLink();
            componentArticlesDataQuoteCateLink.setHref(cateHref).setTarget(componentArticlesDataConfig.getCtarget());

            String dataTitle = sArticle.getTitle();
            String dataInfo = sArticle.getSynopsis();
            if (StringUtils.isEmpty(dataInfo)) {
                dataInfo = "";
            }

            String cateTitle = "";
            if (categoryQuote != null && categoryQuote.getSCategories() != null) {
                cateTitle = categoryQuote.getSCategories().getName();
            }
            Date datetime = sArticle.getReleasedAt();

            ComponentArticlesDataQuote componentArticlesDataQuote = new ComponentArticlesDataQuote();

            componentArticlesDataQuote.setCateLink(componentArticlesDataQuoteCateLink).setCateTitle(cateTitle).setDataInfo(dataInfo).setDataTitle(dataTitle)
                    .setDatetime(datetime).setImage(componentArticlesDataQuoteImage).setLink(componentArticlesDataQuoteLink);

            quote.add(componentArticlesDataQuote);

            DateString dateString = new DateString();
            LocalDateTime localDateTime = LocalDateTime.ofInstant(datetime.toInstant(), ZoneId.systemDefault());
            int year = localDateTime.getYear();
            int monthValue = localDateTime.getMonthValue();
            int dayOfMonth = localDateTime.getDayOfMonth();
            int hour = localDateTime.getHour();
            int minute = localDateTime.getMinute();
            int second = localDateTime.getSecond();
            dateString.setYear(String.valueOf(year)).setMonth(monthValue < 10 ? "0" + monthValue : String.valueOf(monthValue))
                    .setDay(dayOfMonth < 10 ? "0" + dayOfMonth : String.valueOf(dayOfMonth)).setHours(hour < 10 ? "0" + hour : String.valueOf(hour))
                    .setMinutes(minute < 10 ? "0" + minute : String.valueOf(minute)).setSeconds(second < 10 ? "0" + second : String.valueOf(second))
                    .setMonthsEng(monthsInEng[monthValue - 1]);
            date.add(dateString);
        }

        String titleStyle = componentArticlesData.getTitleStyle();
        if (StringUtils.hasText(titleStyle)) {
            titleStyle = "style=\"" + titleStyle + "\"";
        }

        Map<String, Object> mapData = new HashMap<>();
        mapData.put("comid", siteComponent.getComponent().getId());
        mapData.put("id", "product-id-" + DigestUtils.md5DigestAsHex(String.valueOf(siteComponent.getComponent().getId()).getBytes()));
        mapData.put("titleStyle", titleStyle);
        mapData.put("showSort", showSort);
        mapData.put("showTime", showTime);
        mapData.put("ratio", ratio);
        mapData.put("viewDetaits", viewDetaits);
        mapData.put("vis", vis);
        mapData.put("quote", quote);
        mapData.put("date", date);

        StringWriter render = basicUdin.render(name, "articles_" + componentArticlesData.getTheme(), mapData);
        stringBuilder.append(render);

        return stringBuilder;
    }

    @Data
    @Accessors(chain = true)
    public static class DateString {
        private String year;
        private String month;
        private String day;
        private String hours;
        private String minutes;
        private String seconds;
        private String monthsEng;
    }

}
